import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.express as px
import datetime  # 确保导入 datetime
import pandas as pd

class DashboardBuilder:
    def __init__(self, config):
        self.config = config
        self.colors = self.config.COLORS

    def create_dashboard(self, analysis_results: dict):
        fig = make_subplots(
            rows=3, cols=2,
            specs=[
                [{"type": "scatter", "rowspan": 2}, {"type": "pie"}],
                [None, {"type": "bar"}],
                [{"type": "bar"}, {"type": "bar"}]
            ],
            subplot_titles=(
                "每日流量趋势与转化率",
                "流量来源分布",
                "各来源转化率对比",
                "设备类型分析",
                "周流量模式",
                "热门产品排行"
            ),
            vertical_spacing=0.12,
            horizontal_spacing=0.15
        )

        # 1. 每日流量趋势
        trend_df = analysis_results['daily_trend'].toPandas()
        fig.add_trace(
            go.Scatter(
                x=trend_df['date'],
                y=trend_df['total_visits'],
                mode='lines+markers',
                name='访问量',
                line=dict(color=self.colors['secondary'], width=3),
                hovertemplate='%{x|%m-%d}<br>访问量: %{y:.0f}'
            ),
            row=1, col=1
        )

        fig.add_trace(
            go.Scatter(
                x=trend_df['date'],
                y=trend_df['avg_conversion_rate'] * 100,
                mode='lines',
                name='转化率',
                yaxis='y2',
                line=dict(color=self.colors['primary'], width=3, dash='dot'),
                hovertemplate='%{x|%m-%d}<br>转化率: %{y:.2f}%'
            ),
            row=1, col=1
        )

        # 2. 流量来源分布
        source_df = analysis_results['source_performance'].toPandas()
        fig.add_trace(
            go.Pie(
                labels=source_df['traffic_source'],
                values=source_df['total_visits'],
                hole=0.4,
                marker=dict(colors=px.colors.qualitative.Pastel),
                textinfo='percent+label',
                hoverinfo='label+value+percent',
                name='流量来源',
                showlegend=False
            ),
            row=1, col=2
        )

        # 3. 各来源转化率
        fig.add_trace(
            go.Bar(
                x=source_df['traffic_source'],
                y=source_df['avg_conversion_rate'] * 100,
                marker=dict(color=px.colors.qualitative.Pastel),
                text=[f"{x * 100:.2f}%" for x in source_df['avg_conversion_rate']],
                textposition='auto',
                name='转化率',
                showlegend=False
            ),
            row=2, col=2
        )

        # 4. 设备类型分析
        device_df = analysis_results['device_performance'].toPandas()
        fig.add_trace(
            go.Bar(
                x=device_df['device_type'],
                y=device_df['total_visits'],
                marker=dict(color=[self.colors['secondary'],
                                   self.colors['primary'],
                                   self.colors['accent']]),
                text=device_df['total_visits'],
                textposition='auto',
                name='设备访问量',
                showlegend=False
            ),
            row=3, col=1
        )

        # 5. 周流量模式
        weekday_df = analysis_results['weekday_pattern'].toPandas()
        weekday_order = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        weekday_df['weekday'] = pd.Categorical(weekday_df['weekday'], categories=weekday_order, ordered=True)
        weekday_df = weekday_df.sort_values('weekday')

        fig.add_trace(
            go.Scatter(
                x=weekday_df['weekday'],
                y=weekday_df['total_visits'],
                mode='lines+markers',
                name='周访问量',
                line=dict(color=self.colors['dark'], width=3),
                hovertemplate='%{x}<br>访问量: %{y}',
                showlegend=False
            ),
            row=3, col=1
        )

        # 6. 热门产品排行
        product_df = analysis_results['top_products'].toPandas()
        fig.add_trace(
            go.Bar(
                x=product_df['count'],
                y=product_df['product'],
                orientation='h',
                marker=dict(color=px.colors.qualitative.Pastel),
                text=product_df['count'],
                textposition='auto',
                name='热门产品',
                showlegend=False
            ),
            row=3, col=2
        )

        # 更新布局
        fig.update_layout(
            title_text='<b>好想来零食销售项目流量分析看板</b>',
            title_font_size=24,
            title_x=0.5,
            height=1000,
            width=1200,
            template='plotly_white',
            showlegend=True,
            legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
            hovermode='closest',
            margin=dict(l=50, r=50, t=100, b=50),
            # 修复后的时间戳注释
            annotations=[
                dict(
                    text=f"数据更新时间: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}",
                    showarrow=False,
                    xref='paper', yref='paper',
                    x=0.5, y=-0.08, xanchor='center', yanchor='top'
                )
            ]
        )

        # 更新坐标轴和标题
        fig.update_yaxes(title_text="访问量", row=1, col=1)
        fig.update_yaxes(title_text="转化率 (%)", secondary_y=True, row=1, col=1)
        fig.update_yaxes(title_text="访问量", row=3, col=1)

        fig.update_xaxes(title_text="日期", row=1, col=1)
        fig.update_xaxes(title_text="流量来源", row=2, col=2)
        fig.update_xaxes(title_text="设备类型", row=3, col=1)
        fig.update_xaxes(title_text="出现次数", row=3, col=2)

        return fig